#!/bin/bash
echo "system user" `whoami`
# 设置环境变量（公共逻辑）
export PUB_HOSTED_URL="https://pub.flutter-io.cn"
export FLUTTER_STORAGE_BASE_URL="https://storage.flutter-io.cn"
export http_proxy=127.0.0.1:7896
export https_proxy=127.0.0.1:7896


# 检查sed/gsed可用性
check_sed() {
    echo "测试 sed 命令..."
    sed --version || gsed --version || {
        echo "错误：未找到 sed 或 gsed 命令"
        exit 1
    }

    # 获取Git日志
    git_log=$(env GIT_PAGER=cat git log -1)
    echo "最后一次提交日志:"
    echo "$git_log"

    # 获取脚本路径
    echo -e "\n当前脚本完整路径:"
    script_path=$(readlink -f "$0")
    echo "$script_path"
}

# 构建APK主函数
startBuildApk() {
    local channel="$1"
    local version="$2"
    local versionCode="$3"
    local abi="$4"
    local appName="$5"
    local env="$6"
    local flavor="$7"
    local adInitStartTime="$8"
    local adInitEndTime="$9"
    local oaidStartTime="${10}"
    local oaidEndTime="${11}"
    local junkCodeLink="${12}"
    local icon="${13}"


    # 新增部分：校对 build.gradle 的 Maven 仓库逻辑
    BUILD_GRADLE="./android/build.gradle"
    # 验证路径
    if [ ! -f "$BUILD_GRADLE" ]; then
        echo "错误：build.gradle 路径无效，当前目录：$(pwd)"
        exit 1
    fi
    REPOSITORY_PANGLE="https://artifact.bytedance.com/repository/pangle"
    REPOSITORY_VOLCENGINE="https://artifact.bytedance.com/repository/Volcengine/"
    REPOSITORY_HUAWEI="https://developer.huawei.com/repo"
    REPOSITORY_HIHONOR="https://developer.hihonor.com/repo"

    # 检查并添加 pangle 仓库（兼容 macOS 和 Linux）
    if ! grep -q "$REPOSITORY_PANGLE" "$BUILD_GRADLE"; then
        echo "添加 pangle 仓库到 build.gradle"
        # macOS 和 Linux 兼容写法
        sed -i.bak '/allprojects {/,/}/ {
            /repositories {/a \
            maven{url "'"$REPOSITORY_PANGLE"'"}
        }' "$BUILD_GRADLE" && rm -f "$BUILD_GRADLE.bak"
    fi

    # 检查并添加 Volcengine 仓库
    if ! grep -q "$REPOSITORY_VOLCENGINE" "$BUILD_GRADLE"; then
        echo "添加 Volcengine 仓库到 build.gradle"
        sed -i.bak '/allprojects {/,/}/ {
            /repositories {/a \
            maven{url "'"$REPOSITORY_VOLCENGINE"'"}
        }' "$BUILD_GRADLE" && rm -f "$BUILD_GRADLE.bak"
    fi

    # 检查并添加 Huawei 仓库
    if ! grep -q "$REPOSITORY_HUAWEI" "$BUILD_GRADLE"; then
        echo "添加 Huawei 仓库到 build.gradle"
        sed -i.bak '/allprojects {/,/}/ {
            /repositories {/a \
            maven{url "'"$REPOSITORY_HUAWEI"'"}
        }' "$BUILD_GRADLE" && rm -f "$BUILD_GRADLE.bak"
    fi

    # 检查并添加 HiHonor 仓库
    if ! grep -q "$REPOSITORY_HIHONOR" "$BUILD_GRADLE"; then
        echo "添加 HiHonor 仓库到 build.gradle"
        sed -i.bak '/allprojects {/,/}/ {
            /repositories {/a \
            maven{url "'"$REPOSITORY_HIHONOR"'"}
        }' "$BUILD_GRADLE" && rm -f "$BUILD_GRADLE.bak"
    fi


    # 新增应用图标逻辑
    ensureIcon "$icon";

    # 控制Flutter命令前缀
    local isForRemote=true
    local flutterCmd="flutter"
    [[ "$isForRemote" == "true" ]] && flutterCmd="/root/flutter/flutter3190/flutter/bin/flutter"

    # 设置Flutter环境变量
    export PUB_HOSTED_URL="https://pub.flutter-io.cn"
    export FLUTTER_STORAGE_BASE_URL="https://storage.flutter-io.cn"

    # 处理混淆代码
    if [ -z "$junkCodeLink" ]; then
        echo "未提供混淆代码链接，跳过下载"
        PROJECT_DIR=$(dirname "$0")
        targetPath="$PROJECT_DIR/android/app/libs/"
        junkFile="${targetPath}junk-release.aar"
        [ -f "$junkFile" ] && rm -f "$junkFile"
    else
        PROJECT_DIR=$(dirname "$0")
        targetPath="$PROJECT_DIR/android/app/libs/"
        [ ! -d "$targetPath" ] && mkdir -p "$targetPath"
        wget -O "${targetPath}junk-release.aar" "$junkCodeLink"
    fi

    # 准备构建参数
    local envParam="true"
    [[ "$env" =~ "Release" ]] || envParam="false"

    # 创建输出目录
    local apkPath="./output/${appName}"
    [ ! -d "$apkPath" ] && mkdir -p "$apkPath"

    # 动态构建dart-define参数数组
    local dart_defines=(
            "--dart-define=APP_CHANNEL=$channel"
            "--dart-define=NAME=$appName"
            "--dart-define=IS_PRODUCT=$envParam"
        )

    # 添加条件判断的处理逻辑
    [[ -n "$adInitStartTime" ]] && dart_defines+=("--dart-define=AD_INIT_START_TIME=$adInitStartTime")
    [[ -n "$adInitEndTime" ]] && dart_defines+=("--dart-define=AD_INIT_END_TIME=$adInitEndTime")
    [[ -n "$oaidStartTime" ]] && dart_defines+=("--dart-define=OAID_START_TIME=$oaidStartTime")
    [[ -n "$oaidEndTime" ]] && dart_defines+=("--dart-define=OAID_END_TIME=$oaidEndTime")

    # 执行构建命令
    echo "开始构建: $appName (渠道: $channel, 版本: $version)"
    rm -rf pubspec.lock
    # 清理Gradle缓存（精确清理模式）
    # echo "正在清理Gradle依赖缓存（位置：$HOME/.gradle/caches/modules-2/）..."
    # time rm -rf "$HOME/.gradle/caches/modules-2/"
    # echo "依赖缓存清理完成，原占用空间：$(du -sh $HOME/.gradle/caches/modules-2/ 2>/dev/null | cut -f1 || echo '0B')"

    # echo "正在清理Gradle构建缓存（位置：$HOME/.gradle/caches/transforms-2/）..."
    # time rm -rf "$HOME/.gradle/caches/transforms-2/"
    # echo "构建缓存清理完成，原占用空间：$(du -sh $HOME/.gradle/caches/transforms-2/ 2>/dev/null | cut -f1 || echo '0B')"

    $flutterCmd doctor
    $flutterCmd clean
    $flutterCmd precache
    $flutterCmd build apk \
        --flavor="${flavor}${abi}" \
        "${dart_defines[@]}" \
        --build-name="$version" \
        --build-number="$versionCode" \
        --release

    # 复制APK文件
    sleep 5s
    cp -R build/app/outputs/apk/"${flavor}${abi^}"/release/*.apk \
        "${apkPath}/${version}-${channel}-${flavor}${abi}-release.apk"

    echo "构建完成: ${apkPath}/${version}-${channel}-${flavor}${abi}-release.apk"
}

function ensureIcon() {
    local icon_url="$1"
    local download_success=false

    #↓↓↓↓↓↓↓↓↓↓↓↓↓↓ 新增校验逻辑 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    # 参数检查
    if [[ -z "$icon_url" ]]; then
        echo "没有提供应用图标下载地址" >&2
        return 1
    fi

    # URL合法性校验（匹配http/https协议头）
    if [[ ! "$icon_url" =~ ^https?://.+ ]]; then
        echo "错误：非法的URL格式，必须使用http://或https://开头" >&2
        return 1
    fi
    #↑↑↑↑↑↑↑↑↑↑↑↑↑ 新增校验逻辑 ↑↑↑↑↑↑↑↑↑↑↑↑↑

    # 提取文件名和后缀
    local filename
    filename=$(basename "$icon_url" | sed 's/[?#].*//')
    local extension="${filename##*.}"

    # 处理无后缀情况
    if [ "$extension" = "$filename" ]; then
        extension="png"
    fi

    # 临时文件命名
    local temp_file="ic_launcher_from_remote.$extension"

    # 下载函数
    downloadIcon() {
        if curl -sSL -o "$temp_file" "$icon_url"; then
            if file "$temp_file" | grep -q 'image data'; then
                echo "图标下载成功: $temp_file"
                download_success=true
            else
                echo "错误：下载内容不是有效图片"
                rm -f "$temp_file"
                return 1
            fi
        else
            echo "错误：图标下载失败"
            return 1
        fi
    }

    # 替换函数
    replaceIcons() {
        local target_dir="$1"
        local name_pattern="$2"

        if [ -d "$target_dir" ]; then
            find "$target_dir" -maxdepth 1 -name "$name_pattern*" -type f | while read -r file; do
                if cp -f "$temp_file" "$file"; then
                    echo "已更新: $file"
                else
                    echo "警告：$file 更新失败"
                fi
            done
        else
            echo "警告：目录不存在 $target_dir"
            return 1
        fi
    }

    # 主执行流程
    if downloadIcon; then
        replaceIcons "./android/app/src/main/res/mipmap-xhdpi/" "ic_launcher"
        replaceIcons "./android/app/src/main/res/mipmap-xxhdpi/" "ic_launcher"
        replaceIcons "./android/app/src/main/res/mipmap-xxxhdpi/" "ic_launcher"
        replaceIcons "./assets/images/mine/" "icon_app"
        replaceIcons "./assets/imagesbus/mine/" "icon_app"
        replaceIcons "./packages/pkg_panda/assets/drawable/" "icon_splash_logo"
        replaceIcons "./packages/pkg_klear/assets/images/mine/" "icon_app"
        replaceIcons "./packages/pkg_helper/assets/images/mine/" "icon_app"
        replaceIcons "./packages/pkg_pass/assets/images/mine/" "icon_app"
    fi

    # 清理临时文件
    [ -f "$temp_file" ] && rm -f "$temp_file"
    return $(( download_success ? 0 : 1 ))
}



# JSON模式处理函数
process_json_mode() {
    local config_file="$1"
    echo "检测到配置文件，采用JSON模式"
    echo "原始JSON内容: $(cat "$config_file")"
    if ! command -v jq &> /dev/null; then
        echo "错误：未找到jq命令，请先安装（sudo apt-get install jq）"
        exit 1
    fi

    # 安全获取数组长度
    local length=0
    length=$(jq '.task | length' "$config_file" 2>/dev/null || echo 0)
    if [ "$length" -eq 0 ]; then
        echo "警告：JSON配置为空，回退到参数模式"
        return 1
    fi

    for ((index=0; index<length; index++)); do
        # 获取channels字段（符合ShellCheck规范）
        local raw_channels
        if ! raw_channels=$(jq -r ".task[$index].channels" "$config_file" 2>&1); then
            echo "[跳过]警告：解析.task[$index].channels失败 - ${raw_channels#jq: }" >&2
            continue
        elif [ -z "$raw_channels" ]; then
            echo "[跳过]提示：.task[$index].channels为空值" >&2
            continue
        fi

        # 渠道拆分（兼容bash4.2）
        OLD_IFS=$IFS
        IFS=',' read -ra channel_array <<< "$raw_channels"
        IFS=$OLD_IFS

        for single_channel in "${channel_array[@]}"; do
            echo "正在处理第$((index+1))个构建任务，渠道号: $single_channel..."

            # 声明变量（与JSON字段名保持一致的驼峰命名）
            local versionName
            local versionCode
            local abi
            local appName
            local env
            local productFlavor
            local adInitStartTime
            local adInitEndTime
            local oaidStartTime
            local oaidEndTime
            local junkCodeLink

            # 提取JSON字段（变量名与JSON键名完全对应）
            versionName=$(jq -r ".task[$index].versionName" "$config_file")
            versionCode=$(echo "$versionName" | tr -d '.')  # 从versionName生成versionCode
            abi=$(jq -r ".task[$index].abi" "$config_file")
            appName=$(jq -r ".task[$index].appName" "$config_file")
            env=$(jq -r ".task[$index].env" "$config_file")
            # 新增逻辑：如果productFlavor是tax，则在versionCode上加999
            productFlavor=$(jq -r ".task[$index].productFlavor" "$config_file")
            if [ "$productFlavor" == "tax" ]; then
               versionCode=$((versionCode + 999))
            fi
            adInitStartTime=$(jq -r ".task[$index].adInitStartTime" "$config_file")
            adInitEndTime=$(jq -r ".task[$index].adInitEndTime" "$config_file")
            oaidStartTime=$(jq -r ".task[$index].oaidStartTime" "$config_file")
            oaidEndTime=$(jq -r ".task[$index].oaidEndTime" "$config_file")
            junkCodeLink=$(jq -r ".task[$index].junkCodeLink // \"\"" "$config_file")
            icon=$(jq -r ".task[$index].icon // \"\"" "$config_file")

            # 打印参数（保持带编号输出）
            echo "[1] 输入的渠道号参数=$single_channel"
            echo "[2] 输入的版本号参数=$versionName"
            echo "[3] 生成的VersionCode参数=$versionCode"
            echo "[4] 输入的Abi参数=$abi"
            echo "[5] 输入的应用名称参数=$appName"
            echo "[6] 输入的env参数=$env"
            echo "[7] 输入的flavor参数=$productFlavor"
            echo "[8] 输入的adInitStartTime参数=$adInitStartTime"
            echo "[9] 输入的adInitEndTime参数=$adInitEndTime"
            echo "[10] 输入的oaidStartTime参数=$oaidStartTime"
            echo "[11] 输入的oaidEndTime参数=$oaidEndTime"
            echo "[12] 输入的junkCodeLink参数=$junkCodeLink"
            echo "[13] 输入的应用图标参数=$icon"

            # 调用构建函数
            startBuildApk "$single_channel" "$versionName" "$versionCode" "$abi" "$appName" "$env" \
                           "$productFlavor" "$adInitStartTime" "$adInitEndTime" "$oaidStartTime" \
                           "$oaidEndTime" "$junkCodeLink" "$icon"
        done
    done
    exit 0
}



# 参数模式处理函数
process_args_mode2() {
    echo "未检测到配置文件，采用参数模式"

    # 将每个参数转换为数组
    local channels=() versionNames=() versionCodes=() abis=() appNames=() envs=()
    local productFlavors=() adInitStartTimes=() adInitEndTimes=() oaidStartTimes=()
    local oaidEndTimes=() junkCodeLinks=()

    IFS=',' read -ra channels <<< "${1:-}"
    IFS=',' read -ra versionNames <<< "${2:-}"
    IFS=',' read -ra versionCodes <<< "${3:-}"
    IFS=',' read -ra abis <<< "${4:-}"
    IFS=',' read -ra appNames <<< "${5:-}"
    IFS=',' read -ra envs <<< "${6:-Release}"
    IFS=',' read -ra productFlavors <<< "${7:-}"
    IFS=',' read -ra adInitStartTimes <<< "${8:-}"
    IFS=',' read -ra adInitEndTimes <<< "${9:-}"
    IFS=',' read -ra oaidStartTimes <<< "${10:-}"
    IFS=',' read -ra oaidEndTimes <<< "${11:-}"
    IFS=',' read -ra junkCodeLinks <<< "${12:-}"

    # 获取所有数组的长度并确定最大长度
    local max_length=0
    declare -a param_lengths=(
        "${#channels[@]}" "${#versionNames[@]}" "${#versionCodes[@]}" "${#abis[@]}"
        "${#appNames[@]}" "${#envs[@]}" "${#productFlavors[@]}" "${#adInitStartTimes[@]}"
        "${#adInitEndTimes[@]}" "${#oaidStartTimes[@]}" "${#oaidEndTimes[@]}" "${#junkCodeLinks[@]}"
    )
    for len in "${param_lengths[@]}"; do
        if (( len > max_length )); then
            max_length=$len
        fi
    done

    # 兼容Bash 4.2的数组扩展函数
    expand_array() {
        local arr_name=$1
        local arr_size first_elem
        eval "arr_size=\${#${arr_name}[@]}"
        if (( arr_size == 1 && max_length > 1 )); then
            eval "first_elem=\${${arr_name}[0]-}"
            if [[ -z "$first_elem" ]]; then
                eval "${arr_name}=()"
                for ((i=0; i<max_length; i++)); do
                    eval "${arr_name}[\$i]=\"\""  # 赋空值而非未定义
                done
            else
                eval "${arr_name}=()"
                for ((i=0; i<max_length; i++)); do
                    eval "${arr_name}[\$i]=\"\$first_elem\""
                done
            fi
        fi
    }


    expand_array channels
    expand_array versionNames
    expand_array versionCodes
    expand_array abis
    expand_array appNames
    expand_array envs
    expand_array productFlavors
    expand_array adInitStartTimes
    expand_array adInitEndTimes
    expand_array oaidStartTimes
    expand_array oaidEndTimes
    expand_array junkCodeLinks

    # 检查必填参数是否存在且非空
    for i in "${!channels[@]}"; do
        if [[ -z "${channels[i]}" || -z "${versionNames[i]}" || -z "${versionCodes[i]}" ||
              -z "${abis[i]}" || -z "${appNames[i]}" ]]; then
            echo "错误：索引 $i 处缺少必要参数（渠道/版本/ABI/应用名）"
            exit 1
        fi
    done

    # 遍历所有构建任务
    for ((i=0; i<max_length; i++)); do
        echo "正在构建任务 $((i+1)):"
        echo "渠道: ${channels[i]}"
        echo "版本名: ${versionNames[i]}"
        echo "版本码: ${versionCodes[i]}"
        echo "ABI: ${abis[i]}"
        echo "应用名: ${appNames[i]}"
        echo "环境: ${envs[i]}"
        echo "Flavor: ${productFlavors[i]}"
        echo "广告初始时间: ${adInitStartTimes[i]-未设置}"
        echo "广告结束时间: ${adInitEndTimes[i]-未设置}"
        echo "OAID开始时间: ${oaidStartTimes[i]-未设置}"
        echo "OAID结束时间: ${oaidEndTimes[i]-未设置}"
        echo "垃圾代码链接: ${junkCodeLinks[i]-未设置}"

        # 调用构建函数
        startBuildApk \
            "${channels[i]}" \
            "${versionNames[i]}" \
            "${versionCodes[i]}" \
            "${abis[i]}" \
            "${appNames[i]}" \
            "${envs[i]}" \
            "${productFlavors[i]}" \
            "${adInitStartTimes[i]}" \
            "${adInitEndTimes[i]}" \
            "${oaidStartTimes[i]}" \
            "${oaidEndTimes[i]}" \
            "${junkCodeLinks[i]}"
    done
}


# 参数模式处理函数
process_args_mode() {
    echo "未检测到配置文件，采用参数模式"
    echo "输入的渠道号参数: $1"
    echo "输入的版本号参数: $2"
    echo "输入的VersionCode参数: $3"
    echo "输入的Abi参数: $4"
    echo "输入的应用名称参数: $5"
    echo "输入的env参数: $6"
    echo "输入的flavor参数: $7"
    echo "输入的adInitStartTime参数: $8"
    echo "输入的adInitEndTime参数: $9"
    echo "输入的oaidStartTime参数: ${10}"
    echo "输入的oaidEndTime参数: ${11}"
    echo "输入的junkCodeLink参数: ${12}"

    # 参数校验（必填参数检查）
    if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ] || [ -z "$5" ]; then
        echo "错误：缺少必要参数（渠道/版本/ABI/应用名）"
        exit 1
    fi

    # 参数处理
    local channels="$1"
    local versionName="$2"
    local versionCode="$3"
    local abi="$4"
    local appName="$5"
    local env="${6:-Release}"
    local productFlavor="$7"
    local adInitStartTime="${8:-}"        # 添加默认空字符串处理
    local adInitEndTime="${9:-}"          # 使用${var:-}语法设置空默认值
    local oaidStartTime="${10:-}"         # 位置参数不存在时自动赋空
    local oaidEndTime="${11:-}"
    local junkCodeLink="${12:-}"

    # IFS解释：临时修改字段分隔符用于拆分渠道列表
    local OLD_IFS="$IFS"  # 保存当前IFS值
    IFS=","               # 将分隔符改为逗号
    read -ra channelArray <<< "$channels"
    IFS="$OLD_IFS"        # 恢复原IFS值

    # 遍历所有渠道进行构建
    for channel in "${channelArray[@]}"; do
        echo "正在构建渠道: $channel"
        startBuildApk "$channel" "$versionName" "$versionCode" "$abi" "$appName" "$env" \
                     "$productFlavor" "$adInitStartTime" "$adInitEndTime" "$oaidStartTime" \
                     "$oaidEndTime" "$junkCodeLink"
    done
}


# 主执行逻辑
main() {
    check_sed
    local config_file
    config_file="$(dirname "$0")/remote_configs.json"
    #config_file="${BASH_SOURCE[0]%/*}/remote_config.json"

    # 输出Bash版本及编译信息
    if (( BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 3) )); then
        echo "tip：需要bash 4.3+版本支持的脚本要小心咯~"
    fi
    echo "当前Bash版本：$BASH_VERSION"
    echo "完整版本信息："
    bash --version | head -n 1

    if [ -f "$config_file" ]; then
        process_json_mode "$config_file" || {
            echo "JSON处理失败，尝试参数模式"
            process_args_mode2 "$@"
        }
    else
        process_args_mode2 "$@"
    fi
}

main "$@"
